package server

import (
	"fmt"
	"io"
	"net"
	"simple_game/app/config"
	"simple_game/app/libs/logger"
	"simple_game/app/utils"
	"strconv"
	"sync"
)

type Server struct {
	Ip   string
	port int
	// 读写锁
	MapLock sync.RWMutex
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:   ip,
		port: port,
	}
	return server
}

func (s *Server) Handler(conn net.Conn) {
	logger.INFO("connect success, ip:", conn.RemoteAddr())
	// todo 创建新玩家actor
	playerActor, err := StartNewPlayerActor(conn, s)
	if err != nil {
		logger.ERROR("StartPlayerActor error,ip:", s.Ip)
		return
	}
	//接受客户端的消息
	go func() {
		for {
			buf, err := utils.RecvData(conn)
			if len(buf) == 0 {
				// 离线
				logger.INFO("disconnect ip:", conn.LocalAddr().String())
				playerActor.Stop()
				return
			}
			if err != nil && err != io.EOF {
				logger.ERROR("conn read err", err)
				return
			}
			if err = playerActor.Actor.SendMail(buf); err != nil {
				logger.ERROR("Actor error:", err)
			}
		}
	}()
}

//ListenMessages  监听message广播消息，一旦有消息的话就发送给在线的user
func (s *Server) ListenMessages() {
	for {
		//chat := <-s.Message

		//将msg 发送给所有在线的user
		s.MapLock.Lock()
		//for _, cli := range s.OnlineMap {
		//	tempTime := time.Unix(chat.CreateTime, 0).Format("2006-01-02 15:04:05")
		//	msg := string(tempTime) + "|世界频道|" + chat.UserName + ":" + chat.Content
		//	cli.MsgChan <- msg
		//
		//bytes := []byte(chat.Content)
		//req := &pt.LoginReq{}
		//_ = proto.Unmarshal(bytes, req)
		//fmt.Println(req)
		//}
		s.MapLock.Unlock()
		// 把消息保存到redis
		//json, _ := json.Marshal(chat)
		//utils.AddChat2Redis(strconv.FormatInt(chat.CreateTime, 10), string(json))
	}
}

func Start() {
	port, _ := strconv.Atoi(config.Conf.Tcp.Port)
	newServer := NewServer(config.Conf.Tcp.Addr, port)
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", newServer.Ip, newServer.port))
	if err != nil {
		logger.ERROR("net listen err!", err)
	} else {
		logger.INFO("simple game tcp listen start suc")
	}
	defer func(listener net.Listener) {
		if err := listener.Close(); err != nil {
			logger.ERROR("Start listener.Close Error:", err)
		}
	}(listener)

	// 监听
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listen accept err", err)
			continue
		}
		newServer.Handler(conn)
	}
}
